#http://www.pyside.org/docs/pyside/PySide/QtGui/QLineEdit.html
#http://matplotlib.sourceforge.net/faq/howto_faq.html#save-transparent-figures
#http://doc.qt.nokia.com/4.7-snapshot/stylesheet-examples.html#qpushbutton-and-images
#http://developer.qt.nokia.com/doc/qt-4.8/stylesheet-reference.html#qtableview-widget
from PySide import QtCore, QtGui
import OpenTonitruum.UI.InterfaceBase
import OpenTonitruum.UI.InterfaceAboutFrom
from OpenTonitruum.UI.InterfaceWrapper import FileDataSourceView
from OpenTonitruum.Controller.Environment import Environment
from OpenTonitruum.Controller.Parameter import *
from OpenTonitruum.Base.DataStructure import Event, Struct
from threading import Thread

class GuiAbout(QtGui.QDialog):
	def __init__(self):
		super(GuiAbout, self).__init__()
		self.ui = OpenTonitruum.UI.InterfaceAboutFrom.Ui_Dialog()
		self.ui.setupUi(self)
		self.addEvents()
	
	def addEvents(self):
		pass

class GuiApplication(QtGui.QMainWindow):
	def __init__(self):
		super(GuiApplication, self).__init__()
		self.ui = OpenTonitruum.UI.InterfaceBase.Ui_MainWindow()
		self.ui.setupUi(self)
		self.addEvents()
		self.setupWidgets()
		self.runWidgets()
	
	def addEvents(self):
		#self.ui.actionTransmission.triggered.connect(self.viewPanelTransmission)
		self.ui.actionTransmission.triggered.connect(lambda: self.ui.stackedWidget.setCurrentIndex(1))
		#self.ui.actionDataLayers.triggered.connect(self.viewPanelDataLayers)
		self.ui.actionDataLayers.triggered.connect(lambda: self.ui.stackedWidget.setCurrentIndex(0))
		#self.ui.actionHome.triggered.connect(self.viewPanelHome)
		self.ui.actionHome.triggered.connect(lambda: self.ui.stackedWidget.setCurrentIndex(3))
		#self.ui.actionSelectSource.triggered.connect(self.viewPanelSource)
		self.ui.actionSelectSource.triggered.connect(lambda: self.ui.stackedWidget.setCurrentIndex(2))
		self.ui.actionTopics_help.triggered.connect(self.viewHelpDialog)
		self.ui.actionAbout.triggered.connect(self.viewHelpDialog)
		
		#self.ui.actionExecute.toggled.connect(self.toggleExecuteSimulation)
		
		self.ui.lineEditDataSource.textEdited.connect(self.loadSourceFiles)
		#self.ui.lineEditDataSource.textEdited.connect(lambda: self.parameters.setValue("EnvironmentRunner.parameters.sourceFilename", self.ui.lineEditDataSource.text().strip()))
		
		self.ui.toolButtonDataSourcePath.clicked.connect(self.openDataSourceDirectory)
		
		QtCore.QObject.connect(self.ui.actionExecute, QtCore.SIGNAL("triggered(bool)"), lambda b: (self.ui.actionRun_simulation.trigger() if b else self.ui.actionStop_simulation.trigger() ))
		
		QtCore.QObject.connect(self.ui.actionRun_simulation, QtCore.SIGNAL("triggered()"), lambda: self.ui.actionStop_simulation.setEnabled(True))
		QtCore.QObject.connect(self.ui.actionRun_simulation, QtCore.SIGNAL("triggered()"), lambda: self.ui.actionRun_simulation.setDisabled(True))
		QtCore.QObject.connect(self.ui.actionRun_simulation, QtCore.SIGNAL("triggered()"), lambda: self.ui.actionExecute.setChecked(True))
		
		QtCore.QObject.connect(self.ui.actionStop_simulation, QtCore.SIGNAL("triggered()"), lambda: self.ui.actionRun_simulation.setEnabled(True))
		QtCore.QObject.connect(self.ui.actionStop_simulation, QtCore.SIGNAL("triggered()"), lambda: self.ui.actionStop_simulation.setDisabled(True))
		QtCore.QObject.connect(self.ui.actionStop_simulation, QtCore.SIGNAL("triggered()"), lambda: self.ui.actionExecute.setChecked(False))
		
		self.ui.actionStop_simulation.triggered.connect(self.stopSimulation)
		self.ui.actionRun_simulation.triggered.connect(self.runSimulation)
		self.ui.actionCompared_analysis.triggered.connect(self.runComparedSimulation)
        
	@QtCore.Slot()
	def viewHelpDialog(self):
		if self.guihelp is None:
			self.guihelp = GuiAbout()
		self.guihelp.setVisible(True)
	
	@QtCore.Slot()
	def runSimulation(self):
		#QtGui.QMessageBox.information(None, "Simulation", "Run")
		try:
			self.environment.run()
		except ParameterException as e:
			QtGui.QMessageBox.critical(None, "Parameter error", e.message)
			self.ui.actionStop_simulation.trigger()
			
	
	@QtCore.Slot()
	def stopSimulation(self):
		#QtGui.QMessageBox.information(None, "Simulation", "Stop")
		self.environment.stop()
	
	@QtCore.Slot()
	def runComparedSimulation(self):
		pass
	
	@QtCore.Slot()
	def openDataSourceDirectory(self):
		pathname = QtGui.QFileDialog.getExistingDirectory(self, caption = "Data source path", dir = FileDataSourceView.defaultDirectory, options=QtGui.QFileDialog.ShowDirsOnly)
		self.ui.lineEditDataSource.setText(pathname)
		self.loadSourceFiles()
	
	def setupWidgets(self):
		self.environment = Environment(listeners = [])
		self.parameters = ParameterProvider(self.ui.tableWidgetProperty)
		self.file_sources = FileDataSourceView(self.ui.gridLayoutFileSource)
		self.guihelp = None
		
		self.parameters.add(self.environment)
		
		self.ui.actionView_properties.trigger()
		self.file_sources.selected.connect(lambda path: self.parameters.setValue("Environment.parameters.sourceFilename", path))
	
	def runWidgets(self):
		#self.file_sources.run()
		self.loadSourceFiles()
	
	@QtCore.Slot()
	def loadSourceFiles(self):
		if self.ui.lineEditDataSource.text().strip() == "":
			self.ui.lineEditDataSource.setText(FileDataSourceView.defaultDirectory)
		self.file_sources.dirname = self.ui.lineEditDataSource.text()
		self.file_sources.run()
	
	def closeEvent(self, evt):
		self.environment.finalizeThread()

	
class ParameterProvider(ParameterManager):
	def __init__(self, property_table):
		ParameterManager.__init__(self)
		self.property_table = property_table
		self.__index_table = []
		self.__index_values = []
		self.initialize()
		self.__adding = False
	
	def __addRow(self, param):
		self.__adding = True
		self.__index_table.append(param)
		nameItem = QtGui.QTableWidgetItem(param.description)
		nameItem.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignLeft)
		nameItem.setFlags(QtCore.Qt.NoItemFlags)#| QtCore.Qt.ItemIsEditable)
		valueItem = QtGui.QTableWidgetItem(param.value)
		valueItem.setFlags(valueItem.flags() | QtCore.Qt.ItemIsEditable)
		valueItem.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignLeft)
		self.__index_values.append(valueItem)
		row = len(self.__index_table) - 1
		self.property_table.insertRow(row)
		self.property_table.setItem(row, 0, nameItem)
		self.property_table.setItem(row, 1, valueItem)
		self.__adding = False
	
	def initialize(self):
		self.addItem.add(self.__addRow)
		self.property_table.cellChanged.connect(self.onCellChanged)
	
	def onCellChanged(self, row, col):
		if not self.__adding:
			self.__index_table[row].set( self.property_table.item(row, col).text() )
	
	def setValue(self, name, value):
		ParameterManager.setValue(self, name, value)
		for row, param in enumerate(self.__index_table):
			if param.id == name:
				self.__index_values[row].setText(value)